<template>
  <div>
    <van-cell value="历史记录">
      <!-- 使用 right-icon 插槽来自定义标题 -->
      <template #right-icon>
        <van-icon
          @click="delShow = false"
          name="delete"
          v-if="delShow"
        />
        <div
          class="right_text"
          v-else
        >
          <span @click="deleteAllHistory">全部删除</span>
          <span @click="delShow = true">完成</span>
        </div>
      </template>
    </van-cell>
    <van-cell
      :key="item"
      :title="item"
      class="van-ellipsis"
      v-for="item in historyList"
      @click="goSearch(item)"
    >
      <template #right-icon>
        <van-icon
          @click="delHistory(item)"
          name="close"
          v-if="!delShow"
        />
      </template>
    </van-cell>
  </div>
</template>

<script>
import storage from "../../../utils/storage";
export default {
  name: "SearchHistory",
  components: {},
  data() {
    return {
      delShow: true,
      historyList: []
    };
  },
  created() {
    this.historyList = storage.getItem("SEARCH_HISTORY") || [];
    this.$bus.$on("sendSearchList", _ => {
      this.historyList = storage.getItem("SEARCH_HISTORY") || [];
    });
  },
  methods: {
    delHistory(name) {
      let historyArr = storage.getItem("SEARCH_HISTORY");
      let newHistoryArr = historyArr.filter(i => i !== name);
      storage.setItem("SEARCH_HISTORY", newHistoryArr);
      this.historyList = newHistoryArr;
    },
    deleteAllHistory() {
      this.$dialog
        .confirm({
          message: "确认全部删除？"
        })
        .then(() => {
          storage.removeItem("SEARCH_HISTORY");
          this.historyList = []
          this.delShow = true
        })
        .catch(() => {
          // on cancel
        });
    },
    goSearch(val) {
      this.$emit("searchKeyWord", val);
    }
  }
};
</script>

<style scoped lang="stylus">
.van-icon-delete
  display flex
  align-items center

.right_text
  color #969799

  span
    margin-left 7px
</style>